package com.hatom.cameraxhelp.fragment.ocr;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.internal.utils.ImageUtil;
import androidx.camera.view.PreviewView;
import androidx.fragment.app.Fragment;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hatom.cameraxhelp.R;
import com.hatom.cameraxhelp.utils.CameraXHelp;
import com.hatom.cameraxhelp.utils.IDCardOCRHelper;
import com.hatom.cameraxhelp.utils.IDCardUtil;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.Objects;


/**
 * @author tangxianfeng
 * 比较简单的调用方式
 * 可用封装类进行直接回调处理
 */
public class OcrCameraFragment extends Fragment {


    private PreviewView camera_preview;//预览页面


    private CameraXHelp cameraXHelp;//CrameX工具类

    private IDCardOCRHelper ocrHelper;//Ocr识别能力

    private AppCompatTextView ocr_result;

    private View single_OcrView;
    private AppCompatImageView single_resultImg;

    public OcrCameraFragment() {

    }

    public static OcrCameraFragment newInstance() {
        OcrCameraFragment fragment = new OcrCameraFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        XXPermissions.with(requireActivity())
                .permission(Permission.MANAGE_EXTERNAL_STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all){
                            initOcr();
                        }else {
                            ToastUtils.showShort("存储权限未通过，OCR初始化失败");
                        }
                    }
                });

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.camerax_fragment_singleocr, container, false);
        initView(view);
        return view;
    }


    //布局 监听init
    private void initView(View view) {
        camera_preview = view.findViewById(R.id.ocr_camera_preview);
        ocr_result=view.findViewById(R.id.ocr_result);
        single_OcrView=view.findViewById(R.id.single_OcrView);
        single_resultImg=view.findViewById(R.id.single_resultImg);

        cameraXHelp=new CameraXHelp();//初始化工具类对象

        cameraXHelp.setUpCamera(OcrCameraFragment.this,requireActivity(), camera_preview.getSurfaceProvider(), new CameraXHelp.AnalaysListener() {
            @Override
            public void analyze(@NonNull @NotNull ImageProxy imageProxy) {
                if (ocrHelper!=null){
                    detectOCR(imageProxy);
                }

            }

            @Override
            public void error(String error) {

            }
        });
    }
    //初始化Ocr
    private void initOcr() {
        ocrHelper = IDCardOCRHelper.getInstance(requireActivity());
        if (ocrHelper.hasInit()) {
            ocrHelper.close();
        }
        ocrHelper.init();
        if (!ocrHelper.hasInit()) {
            ToastUtils.showShort("扫描算法启动失败");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (ocrHelper != null) {
            ocrHelper.close();//释放OCR资源
        }
    }

    //OCR识别
    @SuppressLint("RestrictedApi")
    public synchronized void detectOCR(@NonNull ImageProxy imageProxy) {
        Bitmap rgbBitmap = null;
        try {
            rgbBitmap = ImageUtils.getBitmap(Objects.requireNonNull(ImageUtil.yuvImageToJpegByteArray(imageProxy, new Rect(0, 0, imageProxy.getWidth(), imageProxy.getHeight()), 80)), 0)
                    .copy(Bitmap.Config.ARGB_8888, true);
        } catch (ImageUtil.CodecFailedException e) {
            e.printStackTrace();
        }
        // 获取数据旋转角
        int rotate = imageProxy.getImageInfo().getRotationDegrees();

        Bitmap rotatebitmap = ImageUtils.rotate(rgbBitmap, rotate, 0, 0);
        float scaleX = (float) rotatebitmap.getWidth()/ camera_preview.getWidth();//进行比例还原
        float scaleY = (float) rotatebitmap.getHeight() / camera_preview.getHeight();

        Bitmap bitmap = ImageUtils.clip(rotatebitmap, (int)(single_OcrView.getX()*scaleX+40),(int)(single_OcrView.getY()*scaleY), (int) (single_OcrView.getWidth()*scaleX-80),  (int) (single_OcrView.getHeight()*scaleY));

        Bitmap finalBitmap = bitmap2Gray(bitmap);
        String value = ocrHelper.doOCRAnalysis(finalBitmap);
        String[] contents = value.split("\n");
        for (String content : contents) {
            if (TextUtils.isEmpty(content) || content.length() < 18) {
                continue;
            }
            //step2 根据空格分割
            String[] subContents = content.split(" ");
            for (String subContent : subContents) {
                if (!TextUtils.isEmpty(subContent) && subContent.length() == 18) {
                    value = subContent;
                    break;
                }
            }
        }
        String result = value;
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                if (IDCardUtil.is18ByteIdCardComplex(result)) {
                    single_resultImg.setImageBitmap(finalBitmap);
                    String resultText="身份证号:"+ result+"\n"+
                            "\n性别:"+IDCardUtil.getSex(result)
                            +"\n年龄:"+IDCardUtil.getAge(result)
                            +"\n出生日期："+IDCardUtil.getBirthday(result)
                            +"\n籍贯："+IDCardUtil.getNativePlace(result);
                    ocr_result.setText(resultText);
                    //识别成功为身份证号
                }
            }
        });
    }
    //灰度化
    public Bitmap bitmap2Gray(Bitmap bmSrc) {
        // 得到图片的长和宽
        int width = bmSrc.getWidth();
        int height = bmSrc.getHeight();
        // 创建目标灰度图像
        Bitmap bmpGray = null;
        bmpGray = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        // 创建画布
        Canvas c = new Canvas(bmpGray);
        Paint paint = new Paint();
        ColorMatrix cm = new ColorMatrix();
        cm.setSaturation(0);
        ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
        paint.setColorFilter(f);
        c.drawBitmap(bmSrc, 0, 0, paint);
        return bmpGray;
    }
}